package com.google.code.sant.util

import java.io.File
import java.net.URL

/**
 * Utility class for classpath operations.
 *
 * @author Sergey Nebolsin
 */
object ClasspathUtils {
  
  /**
   * Returns a list of absolute paths of jars containtd in directory specified by 'dir'.
   */
  def jarsFromDir( dir:String ):List[String] = {
    val libdir = new java.io.File(dir)
    if ( libdir.exists && libdir.isDirectory) {
      libdir.listFiles.toList
          .filter(f => f.isFile && f.getName.endsWith(".jar") )
          .map( f => f.getAbsolutePath() )
    } else Nil
  }

  /**
   * Splits a string by the file path separator (".;lib/smth.jar" -> List(".","lib/smth.jar")
   */
  def pathsFromString(str: String): List[String] = str.split(File.pathSeparator).toList

  /**
   * Converts File to URL.
   */
  def fileToURL(f: File): Option[URL] =
    try { Some(f.toURL) }
    catch { case e => Console.println(e); None }

  /**
   * Converts File.pathSeparator separated string of paths into a List[URL]
   * dropping paths which not exsist.
   */
  def paths(str: String): List[URL] = for (
    file <- pathsFromString(str) map (new File(_)) if file.exists;
    val url = fileToURL(file); if !url.isEmpty
  ) yield url.get
}
